package com.itheima.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.JedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    JedisUtil jedisUtil;
    @Reference
    MemberService memberService;

    /**
     * 1、form表单提交数据的格式 （name=jack&age=18&address=shangshou） 后端用对象接收不需要加注解
     * 2、页面传的是json数据，后端使用map 或者 pojo时 需要加@RequestBody
     * 3、基本类型 & 数组 & MultipartFile 只要保持页面的参数名称和controller方法形参一致就不用加@RequestParam
     * 4、List 不管名字一不一样 必须加@RequestParam
     *
     * @return
     */
    @RequestMapping("/check")
    public Result check(@RequestBody Map map, HttpServletRequest request) {
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //校验验证码
        String redisCode = jedisUtil.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        if (StrUtil.isBlank(redisCode) || !redisCode.equals(validateCode)) {
            return Result.error("验证码错误");
        }
        //查询当前手机号码是不是会员
        Member member = memberService.findByTelephone(telephone);
        if (null == member) {
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            member = memberService.add(member);
        }

        //把用户信息存入session或者cookie
//        request.getSession().setAttribute("userInfo", member);
        //把用户的信息存入redis
        String token = UUID.randomUUID().toString();
        jedisUtil.add(token, 60 * 60 * 24 * 15, JSON.toJSONString(member));
        return Result.success("登入成功", token);
    }
}
